package com.andnnl.ws;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * Created by chenss on 2019/6/27.
 */
@ServerEndpoint(value="/ws/{userId}")
@Component
public class WsTest {
    private Logger logger = LoggerFactory.getLogger(WsTest.class);

    private static String userId;

    //连接时执行
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) throws IOException {
        this.userId = userId;
        logger.info("新连接：{}",userId);
        new Thread(new Runnable() {
            int i=0;
            @Override
            public void run() {
                try {
                    while (i<10) {
                        session.getBasicRemote().sendText("收到 " + userId + " 的消息 " + i++); //回复用户
                        Thread.sleep(1000);
                        System.out.println("---" + i);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //关闭时执行
    @OnClose
    public void onClose(){
        logger.info("连接：{} 关闭",this.userId);
    }

    //收到消息时执行
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        logger.info("收到用户{}的消息{}",this.userId,message);
        session.getBasicRemote().sendText("收到 "+this.userId+" 的消息 "); //回复用户
    }

    //连接错误时执行
    @OnError
    public void onError(Session session, Throwable error){
        logger.info("用户id为：{}的连接发送错误",this.userId);
        error.printStackTrace();
    }
}
